package com.imooc.trading_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.imooc.trading_system.enums.BizCodeEnum;
import com.imooc.trading_system.enums.address.AddressStatusEnum;
import com.imooc.trading_system.model.AddressDO;
import com.imooc.trading_system.mapper.AddressMapper;
import com.imooc.trading_system.model.UserDO;
import com.imooc.trading_system.service.AddressService;
import com.imooc.trading_system.service.UserService;
import com.imooc.trading_system.utils.JsonData;
import com.imooc.trading_system.vo.address.*;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.BAD_QOS;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Feng zhaoxi
 * @since 2022-04-24
 */
@Service
@Slf4j
public class AddressServiceImpl implements AddressService {
    @Autowired
    private UserService userService;
    @Resource
    private AddressMapper addressMapper;

    /**
     * 新增地址
     *
     * @param addAddressReqVO
     * @return
     */
    @Override
    public JsonData addAddress(AddAddressReqVO addAddressReqVO) {
        UserDO user = userService.getLoginUser();
        AddressDO addressDo = new AddressDO();
        addressDo.setUserId(user.getId());
        BeanUtils.copyProperties(addAddressReqVO, addressDo);
        //如果新增的地址为默认地址，则先判断是否已经有默认地址
        if (addressDo.getDefaultStatus() == AddressStatusEnum.DEFAULT_STATUS.getStatus()) {
            //查找数据库是否有默认地址
            AddressDO defaultAddressDO = addressMapper.selectOne(new QueryWrapper<AddressDO>()
                    .eq("user_id", user.getId())
                    .eq("default_status", AddressStatusEnum.DEFAULT_STATUS.getStatus()));
            //有默认地址，则修改以前的默认地址为非默认地址
            if (defaultAddressDO != null) {
                defaultAddressDO.setDefaultStatus(AddressStatusEnum.COMMON_STATUS.getStatus());
                addressMapper.update(defaultAddressDO, new QueryWrapper<AddressDO>()
                        .eq("id", defaultAddressDO.getId()));
            }
        }
        int rows = addressMapper.insert(addressDo);
        log.info("新增收货地址:rows={},data={}", rows, addressDo);
        return JsonData.buildSuccess();
    }

    /**
     * 编辑地址
     *
     * @param editAddressReqVO
     * @return
     */
    @Override
    public JsonData editAddress(EditAddressReqVO editAddressReqVO) {
        UserDO user = userService.getLoginUser();
        //根据id判断是否有对应的地址记录
        AddressDO addressDO = addressMapper.selectOne(new QueryWrapper<AddressDO>()
                .eq("id", editAddressReqVO.getId())
                .eq("user_id", user.getId()));
        if (addressDO == null) {
            return JsonData.buildResult(BizCodeEnum.NO_CORRESPONDING_ADDRESS);
        }
        //修改地址
        UpdateWrapper<AddressDO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", editAddressReqVO.getId());
        addressDO.setReceiveName(editAddressReqVO.getReceiveName());
        addressDO.setPhoneNumber(editAddressReqVO.getPhoneNumber());
        addressDO.setDetailAddress(editAddressReqVO.getDetailAddress());
        //查找数据库是否有默认地址
        AddressDO defaultAddressDO = addressMapper.selectOne(new QueryWrapper<AddressDO>()
                .eq("user_id", user.getId())
                .eq("default_status", AddressStatusEnum.DEFAULT_STATUS.getStatus()));
        //修改的地址需要需改为默认地址
        if (editAddressReqVO.getDefaultStatus() == AddressStatusEnum.DEFAULT_STATUS.getStatus()) {
            //有默认地址，则修改以前的默认地址为非默认地址
            if (defaultAddressDO != null) {
                defaultAddressDO.setDefaultStatus(AddressStatusEnum.COMMON_STATUS.getStatus());
                addressMapper.update(defaultAddressDO, new QueryWrapper<AddressDO>()
                        .eq("id", defaultAddressDO.getId()));
            }
        }
        //当前地址就是默认地址，需要修改为普通地址，无法修改
        if (editAddressReqVO.getDefaultStatus() == AddressStatusEnum.COMMON_STATUS.getStatus() && addressDO.getDefaultStatus() == AddressStatusEnum.DEFAULT_STATUS.getStatus()) {
            return JsonData.buildResult(BizCodeEnum.MUST_HAVE_A_DEFAULT_ADDRESS);
        }
        addressDO.setDefaultStatus(editAddressReqVO.getDefaultStatus());
        int rows = addressMapper.update(addressDO, updateWrapper);
        if (rows == 1) {
            return JsonData.buildSuccess();
        } else {
            return JsonData.buildResult(BizCodeEnum.EDIT_ADDRESS_FAILED);
        }
    }

    /**
     * 删除地址
     *
     * @param deleteAddressReqVO
     * @return
     */
    @Override
    public JsonData deleteAddress(DeleteAddressReqVO deleteAddressReqVO) {
        UserDO user = userService.getLoginUser();
        //根据id判断是否有对应的地址记录
        AddressDO addressDO = addressMapper.selectOne(new QueryWrapper<AddressDO>()
                .eq("id", deleteAddressReqVO.getId())
                .eq("user_id", user.getId()));
        if (addressDO == null) {
            return JsonData.buildResult(BizCodeEnum.NO_CORRESPONDING_ADDRESS);
        }
        int rows = addressMapper.deleteById(deleteAddressReqVO.getId());
        if (rows == 1) {
            return JsonData.buildSuccess();
        } else {
            return JsonData.buildResult(BizCodeEnum.DELETE_ADDRESS_FAILED);
        }
    }

    /**
     * 获取地址
     *
     * @return
     */
    @Override
    public JsonData getAddressList() {
        UserDO user = userService.getLoginUser();
        List<AddressDO> addressDOList = addressMapper.selectList(new QueryWrapper<AddressDO>()
                .eq("user_id", user.getId()));
        List<GetAddressListRespVO> getAddressListRespVOList = addressDOList.stream().map(obj -> {
            GetAddressListRespVO getAddressListRespVO = new GetAddressListRespVO();
            BeanUtils.copyProperties(obj, getAddressListRespVO);
            return getAddressListRespVO;
        }).collect(Collectors.toList());
        return JsonData.buildSuccess(getAddressListRespVOList);
    }

    /**
     * 根据id获取地址详情
     *
     * @return
     */
    @Override
    public JsonData getAddressListById(GetAddressByIdReqVO getAddressByIdReqVO) {
        UserDO user = userService.getLoginUser();
        AddressDO addressDO = addressMapper.selectOne(new QueryWrapper<AddressDO>()
                .eq("id", getAddressByIdReqVO.getId())
                .eq("user_id", user.getId()));
        System.out.println("addressDO:" + addressDO);
        if (addressDO == null) {
            return JsonData.buildResult(BizCodeEnum.NO_CORRESPONDING_ADDRESS);
        }
        GetAddressByIdRespVO getAddressByIdRespVO = new GetAddressByIdRespVO();
        BeanUtils.copyProperties(addressDO, getAddressByIdRespVO);
        return JsonData.buildSuccess(getAddressByIdRespVO);
    }

    /**
     * 获取卖家默认地址
     *
     * @param sellerId
     * @return
     */
    @Override
    public AddressDO getSellerDefaultAddress(int sellerId) {
        return addressMapper.selectOne(new QueryWrapper<AddressDO>()
                .eq("user_id", sellerId)
                .eq("default_status", 1));
    }
}
